#ifndef _WORLD_MASTER_HPP
#define _WORLD_MASTER_HPP
#include "Singleton.hpp"
#include "World.hpp"
#include <chrono>
#include <iostream>
#include <thread>
#include <functional>
#include "Time.hpp"
#define MIN_TICK_TIME 50 // ms
#define MAX_TICK_TIME 30*1000 // 30s

class WorldMaster
{
private:
    WorldMaster() : _stoped(false), _thread(new std::thread(std::bind(&WorldMaster::Run, this))){}
    ~WorldMaster()
    {
        if(_thread)
        {
            _thread->join();
            delete _thread;
            _thread = nullptr;
        }
    }

    WorldMaster(WorldMaster const& other) = delete;
    WorldMaster(WorldMaster&& other) = delete;
    WorldMaster& operator=(WorldMaster const& other) = delete;
    WorldMaster& operator=(WorldMaster&& other) = delete;
public:
    friend class Singleton<WorldMaster>;
public:
    void Run()
    {
        uint32_t minUpdateDiff = MIN_TICK_TIME;
        uint32_t realCurrTime = 0;
        uint32_t realPrevTime = getMSTime();
        while(!_stoped)
        {
            realCurrTime = getMSTime();

            uint32_t diff = realCurrTime - realPrevTime;
            if (diff < minUpdateDiff)
            {
                uint32_t sleepTime = minUpdateDiff - diff;
                if (sleepTime >= MAX_TICK_TIME)
                {
                    // LOG, sWorld->Update执行时间超过最大tick，需要查看
                }
                // sleep until enough time passes that we can update all timers
                std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
                continue;
            }

            sWorld->Update(diff);
            realPrevTime = realCurrTime;
        }

        // stop
        sWorld->Stop();
    }

    void Stop()
    {
        std::cout << "world master stop ..." << std::endl;
        _stoped = true;
    }
private:
    volatile bool _stoped;
    std::thread* _thread;
};

#define sWorldMaster Singleton<WorldMaster>::getInstance()
#endif